import os
import shutil

from PIL import Image
from docx import Document
from docx.shared import Pt


class ParseDocx(object):
    def __init__(self, pattern_path):
        self.docx_pattern = Document(pattern_path)
        self.docx_pattern.add_paragraph("="*40)

    def write_header(self, header):
        self.docx_pattern.add_heading(header, level=1)

    def write_info_suit(self, details, to_zip_dir, title=None, pics=None, title_l=3, whether_img=False):
        """
        写入组件内容
        :param details:
        :param title:
        :param pics:
        :return:
        """
        if title is not None:
            self.docx_pattern.add_heading(title, level=title_l)

        for detail in details:
            self.docx_pattern.add_paragraph(detail)

        if pics is not None:
            for pic_info in pics:
                if whether_img:

                    # 确认插入图片的长宽
                    to_insert_img = Image.open(pic_info)
                    toii_w, toii_h = to_insert_img.size
                    cut_flag = True if toii_w > 500 else False
                    while cut_flag:
                        toii_w *= 0.9
                        toii_h *= 0.9
                        cut_flag = True if toii_w > 500 else False
                    pic_w = round(toii_w, 0)
                    pic_h = round(toii_h, 0)

                    self.docx_pattern.add_picture(pic_info, Pt(pic_w), Pt(pic_h))
                zip_pic_path = os.path.join(to_zip_dir, os.path.basename(pic_info))
                shutil.copy(pic_info, zip_pic_path)

    def save_as(self, save_as_path):
        """
        保存报告到指定路径
        :param save_as_path:
        :return:
        """
        self.docx_pattern.save(save_as_path)
